package com.security.springmvc.interceptor;

import com.security.springmvc.model.UserDto;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserDto userDto = (UserDto) request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
        if (userDto != null && !userDto.getAuthorities().contains("p1") && request.getRequestURI().contains("/r/r1")) {
            writeCustomMessage(response, "对不起，你没有权限访问该资源");
            return false;
        }
        if(userDto != null && !userDto.getAuthorities().contains("p2") && request.getRequestURI().contains("/r/r2")) {
            writeCustomMessage(response, "对不起，你没有权限访问该资源");
            return false;
        }
        return request.getRequestURI().contains("/login") || request.getRequestURI().contains("/") || request.getMethod().equals("GET");
    }

    private void writeCustomMessage(HttpServletResponse response, String message) throws IOException {
        response.setContentType("text/plain;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().write(message);
    }
}
